<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use think\Db;
use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use think\facade\Log as SystemLog;




// 应用公共文件

/**
 * @Title: ajax_return
 * @Description: todo(ajax提交返回状态信息)
 * @param string $info
 * @param string $url
 * @param int $status
 * @param string $data
 * @author 苏晓信
 * @date 2018年1月13日
 * @throws
 */
function ajax_return($code='' , $msg='' , $count = '' , $data=''){

    $result['code']  = $code;
    $result['msg']   = $msg;
    $result['count'] = $count;
    $result['data']  = $data;

    echo json_encode($result,JSON_UNESCAPED_UNICODE );
    exit();

}


/**
 * @Title: ajax_return
 * @Description: todo(ajax提交返回状态信息)
 * @param string $info
 * @param string $url
 * @param int $status
 * @param string $data
 * @author 苏晓信
 * @date 2018年1月13日
 * @throws
 */
function ajax_api($code='' , $msg='' ,  $data='' ,$count = ''){

    $result['code']  = $code;
    $result['msg']   = $msg;
    $result['data']  = $data;
    $result['count']  = $count;

    echo json_encode($result,JSON_UNESCAPED_UNICODE );
    exit();

}


/**
 * 计算两组经纬度坐标 之间的距离
 * params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:m or 2:km); $decimal 小数点截取位数
 * return m or km
 */
function GetDistance($start, $end, $len_type = 2, $decimal = 2)
{
//    define('EARTH_RADIUS', 6378.137);//地球半径
//    define('PI', 3.1415926);
//
//    $start = '117.119373,39.097884';
//    $end   = '117.175199,39.17408';
//
    $lat1 = explode(',',$start)[1]; // 纬度1
    $lng1 = explode(',',$start)[0]; // 经度1
    $lat2 = explode(',',$end)[1]; // 纬度2
    $lng2 = explode(',',$end)[0]; // 经度2


    $radLat1 = $lat1 * PI / 180.0;
    $radLat2 = $lat2 * PI / 180.0;
    $a = $radLat1 - $radLat2;
    $b = ($lng1 * PI / 180.0) - ($lng2 * PI / 180.0);
    $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
    $s = $s * EARTH_RADIUS;
    $s = round($s * 1000);
    if ($len_type > 1)
    {
        $s /= 1000;
    }
    return round($s, $decimal);
}


/*
 * 短信消息发送
 * $mobile 手机号
 * $code   验证码
 */
function sendMSM($mobile,$code)
{
    //这里的路径EXTEND_PATH就是指tp5根目录下的extend目录，系统自带常量。alisms为我们复制api_sdk过来后更改的目录名称
    require_once WEB_PATH. '/../extend/api_sdk/vendor/autoload.php';
    Config::load();             //加载区域结点配置

    $accessKeyId     = 'LTAIhK4X7ZwlCzfE';                  //阿里云短信获取的accessKeyId

    $accessKeySecret = 'UN80XqrmcLZyh62XaqJLOzimFU1XQO';    //阿里云短信获取的accessKeySecret

    //这个个是审核过的模板内容中的变量赋值，记住数组中字符串code要和模板内容中的保持一致
    //比如我们模板中的内容为：你的验证码为：${code}，该验证码5分钟内有效，请勿泄漏！
    $templateParam = array("code" => $code);           //模板变量替换

    $signName = '万享集'; //这个是短信签名，要审核通过

    $templateCode = 'SMS_168805095';   //短信模板ID，记得要审核通过的


    //短信API产品名（短信产品名固定，无需修改）
    $product = "Dysmsapi";
    //短信API产品域名（接口地址固定，无需修改）
    $domain = "dysmsapi.aliyuncs.com";
    //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
    $region = "cn-hangzhou";

    // 初始化用户Profile实例
    $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
    // 增加服务结点
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
    // 初始化AcsClient用于发起请求
    $acsClient = new DefaultAcsClient($profile);

    // 初始化SendSmsRequest实例用于设置发送短信的参数
    $request = new SendSmsRequest();
    // 必填，设置雉短信接收号码
    $request->setPhoneNumbers($mobile);

    // 必填，设置签名名称
    $request->setSignName($signName);

    // 必填，设置模板CODE
    $request->setTemplateCode($templateCode);

    // 可选，设置模板参数
    if ($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }

    //发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);

    //返回请求结果
    $result = json_decode(json_encode($acsResponse), true);
    return $result;
}

/*
 * 通知类短信消息发送
 * $mobile    手机号
 * $parameter 短信模板参数
 * $type      通知类型 : 1 通知附近网点接单提醒 ,
 */
function send_notify($mobile,$type='1',$parameter=[])
{
    //这里的路径EXTEND_PATH就是指tp5根目录下的extend目录，系统自带常量。alisms为我们复制api_sdk过来后更改的目录名称
    require_once WEB_PATH. '/../extend/api_sdk/vendor/autoload.php';
    Config::load();             //加载区域结点配置

    $accessKeyId     = 'LTAIq7zWNmvF3HzM';                  //阿里云短信获取的accessKeyId

    $accessKeySecret = '8acM2txWlEsDhNhepOnhDYuD4vIF5m';    //阿里云短信获取的accessKeySecret

    //这个个是审核过的模板内容中的变量赋值，记住数组中字符串code要和模板内容中的保持一致
    //比如我们模板中的内容为：你的验证码为：${code}，该验证码5分钟内有效，请勿泄漏！
//    if($parameter){
//        $templateParam = array("code" => $parameter);           //模板变量替换
//    }else{
//        $templateParam = '';           //模板变量替换
//    }


    $signName = '优易网泰'; //这个是短信签名，要审核通过

    $templateParam = ''; //模板变量替换 默认设置为空

    if($type == 1){      // 分配新订单给用户
        $templateCode = 'SMS_165693040';   //短信模板ID，记得要审核通过的

    }elseif($type == 2){ //  到货提醒
        $templateParam = ["number" => $parameter['number'],'name'=>$parameter['name']];
        $templateCode = 'SMS_165693039';
    }



    //短信API产品名（短信产品名固定，无需修改）
    $product = "Dysmsapi";
    //短信API产品域名（接口地址固定，无需修改）
    $domain = "dysmsapi.aliyuncs.com";
    //暂时不支持多Region（目前仅支持cn-hangzhou请勿修改）
    $region = "cn-hangzhou";

    // 初始化用户Profile实例
    $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
    // 增加服务结点
    DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", $product, $domain);
    // 初始化AcsClient用于发起请求
    $acsClient = new DefaultAcsClient($profile);

    // 初始化SendSmsRequest实例用于设置发送短信的参数
    $request = new SendSmsRequest();
    // 必填，设置雉短信接收号码
    $request->setPhoneNumbers($mobile);

    // 必填，设置签名名称
    $request->setSignName($signName);

    // 必填，设置模板CODE
    $request->setTemplateCode($templateCode);

    // 可选，设置模板参数
    if ($templateParam) {
        $request->setTemplateParam(json_encode($templateParam));
    }

    //发起访问请求
    $acsResponse = $acsClient->getAcsResponse($request);

    //返回请求结果
    $result = json_decode(json_encode($acsResponse), true);
    return $result;
}

/*
 * 生成订单号
 */
function order_num(){
    $osn = date('YmdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    return $osn;
}


/*
 * 创建时间节点
 * $order_id  订单id
 * $status    状态
 */
function time_node($order_id,$status){

    $data['order_id']    = $order_id;
    $data['create_time'] = date("Y-m-d H:i:s");

    if($status == 1){ // 用户下单
        $data['operator']      = '用户';
        $data['handle_status'] = '用户下单';
    }elseif ($status == 2){
        $data['operator']      = '网点';
        $data['handle_status'] = '网点接单';
    }elseif ($status == 3){
        $data['operator']      = '网点';
        $data['handle_status'] = '网点派单';
    }elseif ($status == 4){
        $data['operator']      = '洗车工';
        $data['handle_status'] = '去往洗车点';
    }elseif ($status == 5){
        $data['operator']      = '洗车工';
        $data['handle_status'] = '到达洗车点';
    }elseif ($status == 6){
        $data['operator']      = '洗车工';
        $data['handle_status'] = '开始洗车';
    }elseif ($status == 7){
        $data['operator']      = '洗车工';
        $data['handle_status'] = '洗车结束';
    }elseif ($status == 8){
        $data['operator']      = '用户';
        $data['handle_status'] = '评价完成';
    }elseif ($status == 9){
        $data['operator']      = '总部';
        $data['handle_status'] = '订单退款';
    }elseif ($status == 10){
        $data['operator']      = '用户';
        $data['handle_status'] = '取消订单';
    }

    $res = Db::name('time_node')->insert($data);
    if($res){
        return 1;
    }else{
        return 1;
    }

}
/**
 * 对象 转 数组
 *
 * @param object $obj 对象
 * @return array
 */
function objectToArray($obj) {
    $obj = (array) $obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array) objectToArray($v);
        }
    }

    return $obj;
}
/**
 * 后台菜单更新链接
 * @param: $controller_name 控制器名    $action_name 方法名 $param 参数
 */
function getMenuLinkurl($controller_name, $action_name, $param)
{
    return url($controller_name . '/' . $action_name, $param);
}
function checkarray($data,$checkdata){
    foreach($data as $key=>$value){
        if(!isset($checkdata[$value])){
            return $value;
        }
    }
    return false;
}
function imgUrlToAbsolute($img = '') {
    if (stripos($img, 'http') === false || stripos($img, 'https' === false)) {
        return getDomain() . $img;
    } else {
        return $img;
    }
}
function getDomain() {
    $request = \think\facade\Request::instance();
    $domin = $request->domain();
    return $domin;
}
//根据条件 去比较找合适进行条件添加查找 $searchType 1 为 准确查找  2为模糊查找
function addWhere($post,$data,$where,$searchType,$name=""){

    if(array_intersect_key($post,$data)){
        foreach (array_intersect_key($post,$data) as $key=>$value){
            if($value!=""){
                if($searchType ==1){
                    $where[] = [$name.$key,"eq",$value];
                }
                if($searchType ==2){
                    $where[] = [$name.$key,"like","%".$value."%"];
                }
            }
        }
    };
    return $where;
}
/**
 * 修改我的余额并且增加日志
 * @apiError 320 增加余额日志失败
 * @apiError 321 变动余额失败
 * @author aurora
 * @date 2018-10-30
 * @param int $user_id 用户唯一标识
 * @param string $type 变动类型
 * @param float $money 余额变动 大于0为加  小于0为减
 * @param string $show_text 展示文本
 * @param int $relation_id 关联信息ID
 * @param string $remark 预留字段
 * @param int $is_startTrans 默认不开启事务 0：不开启事务  1：开启事务
 * @return \think\response\Json
 * @throws \think\Exception
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function changeLog($user_id, $type, $money, $show_text = '', $relation_id = 0, $is_startTrans = 0)
{
    $money_my_model = new \app\admin\model\UserMoneyMy();
    $money_log_model = new \app\admin\model\UserMoneyLog();

    $my_money = $money_my_model->findOne([['user_id','eq', $user_id]]);

    if (empty($my_money)) { //若该用户没有生成余额，则进行生成，当前余额及累计金额为0
        $money_my_id = $money_my_model->add(['uid' => 1, 'user_id' => $user_id]);
        $my_money = ['id' => $money_my_id, 'money' => 0, 'total_money' => 0];
    }

    if (!empty($is_startTrans)) {//事务
        $money_my_model->startTrans();
    }
    $order_number = "";
    if($type==1||$type==6){// 海淘订单
        $model = new \app\admin\model\OceanOrder();
        $order_number = $model->findOne([['id','eq',$relation_id]],"order_number");
    }
    if($type==2){//提现订单
        $model = new \app\admin\model\UserMoneyWithdraw();
        $order_number = $model->findOne([['id','eq',$relation_id]],"order_number");
    }
    if($type==3){//商城订单
        $model = new \app\index\model\ShopOrder();
        $order_number = $model->findOne([['id','eq',$relation_id]],"order_number");
    }
    if($type==4){//发货订单
        $model = new \app\admin\model\DeliverOrder();
        $order_number = $model->findOne([['id','eq',$relation_id]],"order_number");
    }
    if($type==5){//充值订单
        $model = new \app\admin\model\UserMoneyOrder();
        $order_number = $model->findOne([['id','eq',$relation_id]],"order_number");
    }
    if($type==9){//充值订单
        $model = new \app\index\model\SubstituteOrder();
        $order_number = $model->findOne([['id','eq',$relation_id]],"order_number");
    }
    //余额日志变动
    $log_data = [
        'uid' => 1,
        'user_id' => $user_id,
        'type' => $type,
        'relation_id' => $relation_id,
        'money' => $money,
        'after_money' => $my_money['money'] + $money,
        'show_text' => $show_text,
        'order_number'=>$order_number
//        'remark' => $remark
    ];
    $res = $money_log_model->dataUpdate($log_data);
    if ($res === false) {
        if (!empty($is_startTrans)) {//事务
            $money_my_model->rollback();
        }
        return  sendArray([], 320, '增加余额日志失败');
    }


    //更新用户余额
    $update = [
        'id' => $my_money['id'],
        'money' => $my_money['money'] + $money,
        'total_money' => $money > 0 ? $my_money['total_money'] + $money : $my_money['total_money']
    ];

    $res = $money_my_model->edit($update);
    if ($res === false) {
        if (!empty($is_startTrans)) {//事务
            $money_my_model->rollback();
        }
        return sendArray([], '321', '变动余额失败');
    }

    if (!empty($is_startTrans)) {//事务
        $money_my_model->commit();
    }
    return sendArray();
}
//查询用户当前余额
function search_user_money($user_id){
    $money_my_model = new \app\admin\model\UserMoneyMy();


    $my_money = $money_my_model->findOne([['user_id','eq', $user_id]],"money");
    if (empty($my_money)) { //若该用户没有生成余额，则进行生成，当前余额及累计金额为0
        $my_money = 0;
    }
    return $my_money;
}
/**
 * @param array $data 返回数据
 * @param int $code code码
 * @param string $message 信息
 * @return \think\response\array
 */
function sendArray($data = [], $code = 1, $message = 'SUCCESS') {
    $array = [
        'code' => $code,
        'message' => $message,
        'data' => $data
    ];
    return $array;
}
//给订单加日志
function ocean_log($user_id,$order_number,$remark){
    $log_model  = new \app\admin\model\OceanLog();
    $data =[
        'user_id'=>$user_id,
        'order_number'=>$order_number,
        'remark'      =>$remark,
        'create_time'=>time()
    ];
    $res = $log_model->dataUpdate($data);
    return $res;
}
/**
 * 导出至excel表格        2017-10-15
 * @param: $fileName表格名字   $headArr表头  $data导出数据  $msg批注
 */
function getExcel($fileName, $headArr, $data, $msg = '') {
    //对数据进行检验
    if (empty($data) || !is_array($data)) {
        die("data must be a array");
    }

    //检查文件名
    if (empty($fileName)) {
        die("filename must be existed");
    }

    //获取总列数
    $totalColumn = count($headArr);
    $charColumn = chr($totalColumn + 64);

    // $charColumn = strtoupper(num2alpha($totalColumn));
    $date = date("Y-m-d", time());
    $fileName .= "_{$date}.xls";

    //创建PHPExcel对象
    $objPHPExcel = new \PHPExcel();

    $objPHPExcel->setActiveSheetIndex(0);    //设置当前的sheet  操作第一个工作表
    $objActSheet = $objPHPExcel->getActiveSheet();    //添加数据
    $phpstyle = new \PHPExcel_Style_Color();

    //表头变颜色
    $objActSheet->getStyle('A1:' . $charColumn . '1')->getFont()->getColor()->setARGB($phpstyle::COLOR_BLUE);    //设置颜色
    //设置批注
    if (!empty($msg)) {
        $objActSheet->getStyle('A2')->getFont()->getColor()->setARGB($phpstyle::COLOR_RED);
        $objActSheet->setCellValue('A2', $msg);    //给单个单元格设置内容
        $objActSheet->mergeCells('A2:' . $charColumn . '2');    //合并单元格
    }

    //设置表头
    $key = ord("A");
    $key2 = ord("@"); //@--64
    // $key = foo('a');
    foreach ($headArr as $v) {
        if ($key > ord("Z")) {
            $key2 += 1;
            $key = ord("A");
            $colum = chr($key2) . chr($key); //超过26个字母时才会启用
        } else {
            if ($key2 >= ord("A")) {
                $colum = chr($key2) . chr($key); //超过26个字母时才会启用
            } else {
                $colum = chr($key);
            }
        }
        // $colum = chr($key);
        $objActSheet->setCellValue($colum . '1', $v);
        $objActSheet->getColumnDimension($colum)->setWidth(20);
        $key++;
    }

    //写入数据
    if (!empty($msg)) {
        $column = 3;
    } else {
        $column = 2;
    }
    foreach ($data as $key => $rows) {     //行写入
        $span = ord("A");
        $span2 = ord("@"); //@--64
        foreach ($rows as $keyName => $value) {    // 列写入
            $judge = stristr($keyName, 'img');

            if ($span > ord("Z")) {
                $span2 += 1;
                $span = ord("A");
                $j = chr($span2) . chr($span); //超过26个字母时才会启用
            } else {
                if ($span2 >= ord("A")) {
                    $j = chr($span2) . chr($span); //超过26个字母时才会启用
                } else {
                    $j = chr($span);
                }
            }
            if ($judge === false) {
                $objActSheet->setCellValue($j . $column, $value);
            } else {
                $objActSheet->getRowDimension($column)->setRowHeight(60);    //设置行高

                if (is_array($value)) {
                    $count = count($value);
                    foreach ($value as $k => $v) {
                        if (is_file($v)) {
                            $m = $k + 1;
                            $objDrawing = new \PHPExcel_Worksheet_Drawing();
                            //图片路径,项目目录下就行
                            $objDrawing->setPath($v);
                            $objDrawing->setCoordinates($j . $column);
                            $objDrawing->setWidth(50);
                            $objDrawing->setHeight(50);
                            //图片偏移距离
                            $objDrawing->setOffsetX($m * 10 + $k * 50);
                            $objDrawing->setOffsetY(10);
                            $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                        }
                        //设置列宽
                    }
                    $objPHPExcel->getActiveSheet(0)->getColumnDimension($j)->setWidth(60);
                } else {
                    if (is_file($value)) {
                        $objDrawing = new \PHPExcel_Worksheet_Drawing();
                        $objDrawing->setPath($value);
                        $objDrawing->setWidth(50);
                        $objDrawing->setHeight(50);
                        $objDrawing->setOffsetX(10);
                        $objDrawing->setOffsetY(10);
                        $objDrawing->setCoordinates($j . $column);
                        $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                    } else {
                        $objActSheet->setCellValue($j . $column, $value);
                    }
                }
            }
            $span++;
        }
        $column++;
    }

    //处理中文输出问题
    $fileName = iconv("utf-8", "gb2312", $fileName);

    //接下来当然是下载这个表格了，在浏览器输出就好了
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');

    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('php://output'); //文件通过浏览器下载
}
/**
 * 获取表格数据   2017-10-15
 * @param: $fileName表格名字   $headArr表头  $data导出数据  $msg批注
 */
function getData($file_dir) {
//    vendor('PHPExcel.PHPExcel');
//    $PHPReader = new \PHPExcel_Reader_Excel2007();

//    $array = explode('aliyuncs.com/', $file_dir);
//    $object = $array[1];
//    $array = explode('.', $file_dir);
//    $postfix = end($array);
//    $local_file = './uploads/uid' . $uid . '/download/' . md5(microtime(true)) . '.' . $postfix;
//    createFile($local_file);
//    $file_dir = getObjectToLocalFile($uid, $object, $local_file);
//    $file_dir = $local_file;
    $PHPReader = new \PHPExcel_Reader_Excel5();
    if (!$PHPReader->canRead($file_dir)) {
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($file_dir)) {
            return array(0, '请上传文档');
        }
    }

    //载入文件
    $PHPExcel = $PHPReader->load($file_dir);

    //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
    $currentSheet = $PHPExcel->getSheet(0);

    //获取总行数
    $allRow = $currentSheet->getHighestRow();
    $allColumn = $currentSheet->getHighestColumn();
    $allColumn = ord($allColumn);

    for ($j = 2; $j <= $allRow; $j++) {
        for ($i = 65; $i <= $allColumn; $i++) {
            $colum = chr($i);
            $cell = $currentSheet->getCell($colum . $j)->getValue();
            if ($cell instanceof PHPExcel_RichText) {     //富文本转换字符串
                $cell = $cell->__toString();
            }

            $data[$j][$colum] = $cell;
        }
    }
    return array(1, $data);
}
/**
 * 创建文件夹并赋予777权限 2018-04-16
 * @param string $msg
 */
function createFile($dir) {
    if (substr($dir, -1) == '/') {
        $path = $dir;
    } else {
        $path = dirname($dir);
    }
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }
}
function wxpay($order,$notify_url){
    //$order['total_price'] = 0.01;
    require_once PAY_PATH."lib/WxPay.Api.php";
    require_once PAY_PATH."example/WxPay.NativePay.php";
//    require_once "WxPay.NativePay.php";
    $notify = new NativePay();
    $input = new WxPayUnifiedOrder();
    $input->SetBody("万享集");
    $input->SetAttach("万享集");
    $input->SetOut_trade_no($order['order_number']);
    $input->SetTotal_fee(intval($order['total_price']*100));
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 600));
    $input->SetGoods_tag($order['order_type']);
    $input->SetNotify_url($notify_url);
    $input->SetTrade_type("NATIVE");
    $input->SetProduct_id($order['order_type']);
    $result = $notify->GetPayUrl($input);

    $url2 = $result["code_url"];
    $url2 = urlencode($url2);

    $url2 =  $_SERVER['SERVER_NAME']."/qrcode.php?data=".$url2;
    return $url2;

}
function alipay($order,$notify){
    require_once ALI_PATH . 'config.php';
    require_once ALI_PATH. 'pagepay/service/AlipayTradeService.php';
    require_once ALI_PATH . 'pagepay/buildermodel/AlipayTradePagePayContentBuilder.php';
    //构造参数
    $payRequestBuilder = new \AlipayTradePagePayContentBuilder();
    $payRequestBuilder->setBody("");
    $payRequestBuilder->setSubject("一键代买支付");
    $payRequestBuilder->setTotalAmount($order['total_price']);
    $payRequestBuilder->setOutTradeNo($order['order_number']);
    $alipay_config = array (
        //应用ID,您的APPID。
        'app_id' => "2016121204170280",
        //商户私钥
        'merchant_private_key' => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjSl3RUizRgzBP6PhkDxCudJPss0uUz09kdtUlsEsOdFmZt+w5XykgJ9nQCgATe8EwkUNbUoRPqO6r08MPZfey7hkC43Fwlgt1rh7sQObYfRCVlhN4f93G+3+uZbFT8ybPvaTxkFPkPlAUnAetKsZBvdK1coIL+TqohKC6Fjea0wIDAQAB",
        //异步通知地址
        'notify_url' => "http://mingda.youywt.com/index/login/ali_notify",
        //同步跳转
        'return_url' => "http://www.qqzpz.com/index.php/index/Myorder/index",
        //编码格式
        'charset' => "UTF-8",
        //签名方式
        'sign_type'=>"RSA2",
        //支付宝网关
        'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
        //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
        'alipay_public_key' => "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB",
    );
    $config = array (
        //应用ID,您的APPID。
        'app_id' => "2019011563015673",

        //商户私钥
        'merchant_private_key' => "MIIEpAIBAAKCAQEA19hPudRvgP1MOIkNbM65h68xCVmhjlAOnolN+bOWYDfzQYh3IE5BwXoToJfR1/oYnMxghFslV9ZXYKQlJtIpxrGtVd8U2T1CCyAbQBRNGKIpYS9sHLVgPO0iBdLksT5+EVadZbt21N/U0Vcd7dgJw4dC0MSH61n1C28QbRTLnZHAoVj6lCF1mc4wTVMdpJNv/qNsJEmGBTCZN4YdWrCAWXkvY/Y8ztytQjEuAz61Ygs0dGPTFvedpY01pAAwBf2dkaVkoNREG8bqiXIX9EKznDTxgkzXyEawf5jnon74BbCd1GwNErJItZf1y6V4mPctVzF10FKY/TgQJNhqRhQmLwIDAQABAoIBAGugsgiAlGUmaOZb+LTD1CGDSxlVd0iGRPPqlVYopZgu7f5EdNpIC2PVYooWig1+6Nzu0EXPSSymdYV79AaKj0hDeqIyDaxRbmgrx0rJlLPu0GFkiy05h9Z5jBiJU33KIoS0wuFie9ukDPOh1AuwSRYVkUyWYwwJHDZqWC98She0FmNesnys11sWyLc0RN/jXvtgnLDUfZi1s5NZQ67CEZhV9flLsNUJfURkP3Odry1CyXZaDRHqFbk/C/ymj75E94Sxp38+yLTL9VcgfIjuK3WtSUoQgUpMHcT+EME3dS8sqIMPHyY8Tpf4HIJ9ubY2UjfLhI9qDxjwRe06kIFv8PECgYEA8tMYDmCTXsRH4Er0MtP3J9ay/0YRuZQKHNtcOSeff1aPJxbn2Mte81LqFdRcZE2TK79a68Bg1ALPWOytTlgcC3ru3FekNH/jvd5zbzTWEWSOSWaawWlOANfN0TFxBHgjC3oN05s61Z2jBAo2U+9XHlmpONICi28HfRy5UUd095kCgYEA4452ZatEq7kwVJ2Y4PVxZpmcRjh2LvdBIlF0xDLFS6oDGx2gFQ8jLl55YXYbkU07kzkRrpk0zDnhaPdyXsk1JqCsHKiNzuO5y59Y6CyxMxy0bcBrCEGNau/LeziQP1j9VrFzgdkUaJIWdBjbdZIBke5YNOLPsUgJDdJ+1Ba1CQcCgYEAxYSaU8+Q8Iwenz65BsNOjvRgo68eaeMWmsSAbulhHxaM2VITg1BiSvEOAnW8Nca4SOSdk5jn6mzitsXGbyzSmzADLe6IXkANQ3u4UCQdYQZ3ixNQHLWIwrzH6TsbYHRMpWBB8Pea0vooCPg5murb5Y8vTE3fzgWhhM6hm5DRfzkCgYATYbj34+SPc9CIBHxW/NDR2leTK4/1ZB3qHGIDrAdd8HcfQiC2anmmo2lXQcYLVDa0zXGSG36BvpRSanEVXbHnPlwqfLjHXGIg08uwys20+sbrai4zn9G5v/7m2eR/YMcDMU4TSzgPyBGdhdh7ZRo5IcHlj0P9Z5NN2BXxXpXA1QKBgQDVs4hyi4xQ+WKhHqF9UeL7emUKoIq4XspdEkL+y6ggQ+uT6jNmwpRtyjcIoAv1tsF9KMGnYebbGhIXvMlxFlmk3CH75q0rfapJGJq74ooBxLsdtdqRsbnm1yIdPAB1ozc2NertVzoWIcx0f9qWOXl5Ud5fd7ICcb34I1QcuMeQ9w==",

        //异步通知地址
        'notify_url' => "http://www.qqzpz.com/index.php/index/payment/zfb_payment",

        //同步跳转
        'return_url' => "http://www.qqzpz.com/index.php/index/Myorder/index",

        //编码格式
        'charset' => "UTF-8",

        //签名方式
        'sign_type'=>"RSA2",

        //支付宝网关
        'gatewayUrl' => "https://openapi.alipay.com/gateway.do",

        //支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
        'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA19hPudRvgP1MOIkNbM65h68xCVmhjlAOnolN+bOWYDfzQYh3IE5BwXoToJfR1/oYnMxghFslV9ZXYKQlJtIpxrGtVd8U2T1CCyAbQBRNGKIpYS9sHLVgPO0iBdLksT5+EVadZbt21N/U0Vcd7dgJw4dC0MSH61n1C28QbRTLnZHAoVj6lCF1mc4wTVMdpJNv/qNsJEmGBTCZN4YdWrCAWXkvY/Y8ztytQjEuAz61Ygs0dGPTFvedpY01pAAwBf2dkaVkoNREG8bqiXIX9EKznDTxgkzXyEawf5jnon74BbCd1GwNErJItZf1y6V4mPctVzF10FKY/TgQJNhqRhQmLwIDAQAB",
//    'alipay_public_key'=>'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1kBBx1G0g35J8oL976tHeKYJ7GrM1W5pL9xPeLiYKrC8wTWh0o8M9/NN6fhwwYf+FColM4Ly+Lnt0az8z/d4BN2zj9go3tgTXDGDCgZXF8ojpZROdJ5oR0qwDChTpJSOhy/FUuwGWLtT4XCyeUK0w8SbQ2N408FOG/MxBDPAf1EqMCxvI7jiDSX2CKPFbPIzuf1ad1xswtT5TeVoX7Nf708C1Ror60rz677CvsrPIxbjN1v6cbDCdPNyftGjxPZPoLfq5yp3+6+b0ZY14vbITneZH/ZbBsvQc3kibNIZWfkMQttsRjpB/5grfrr0WeZvcxA9+7FRqFyWDy7F/kZaGwIDAQAB'
    );
    $aop = new \AlipayTradeService($alipay_config);
    /**
     * pagePay 电脑网站支付请求
     * @param $builder 业务参数，使用buildmodel中的对象生成。
     * @param $return_url 同步跳转地址，公网可以访问
     * @param $notify_url 异步通知地址，公网可以访问
     * @return $response 支付宝返回的信息
     */
    $response = $aop->pagePay($payRequestBuilder,"",$notify);
}
function xmltoArray($xml){

    libxml_disable_entity_loader(true);
    $xml=json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $xml;
}
/**
 * 检测手机号    2017-10-15
 */
function isMobilephone($mobilehone = '') {
    if (preg_match("/1[3456789]{1}\d{9}$/", $mobilehone)) {
        return true;
    } else {
        return false;
    }
}
/*
 * 检查邮箱格式是否正确  2018-09-19
 */

function isEmail($email = '') {
    $mode = '/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/';
    if (preg_match($mode, $email)) {
        return true;
    } else {
        return false;
    }
}
/**
 * 检测身份证号    2018-03-21
 */
function isCreditNo($vStr) {
    $vCity = array(
        '11', '12', '13', '14', '15', '21', '22',
        '23', '31', '32', '33', '34', '35', '36',
        '37', '41', '42', '43', '44', '45', '46',
        '50', '51', '52', '53', '54', '61', '62',
        '63', '64', '65', '71', '81', '82', '91'
    );
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr))
        return false;
    if (!in_array(substr($vStr, 0, 2), $vCity))
        return false;
    $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);
    if ($vLength == 18) {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }
    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday)
        return false;
    if ($vLength == 18) {
        $vSum = 0;
        for ($i = 17; $i >= 0; $i--) {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
        }
        if ($vSum % 11 != 1)
            return false;
    }
    return true;
}


/**
 * 将序列化的信息存入到数据库中，进行转换  2017-10-15
 * @param mixed $info 信息    $type 0为序列化，1为反序列化
 */
function serializeMysql($info, $type = 0) {
    if ($type == 0) {
        return addslashes(serialize($info));
    } else {
        return unserialize(stripslashes($info));
    }
}
//根据累计消费 去对用户等级操作  money 即为钱数  user_id 即为用户
function  level_change($user_id,$money){
    $user_model = new \app\admin\model\User();
    $user_info = $user_model->findOne([['id','eq',$user_id]]);
    if($user_info){
        $user_model->where('id','eq',$user_id)->setInc("cumulative_money",$money);
        $money +=$user_info['cumulative_money'];
        $user_level_model = new \app\admin\model\UserLevel();
        $where_level = [
            ['up_money','lt',$money]
        ];
        $level = $user_level_model->where($where_level)->order("sort desc")->find();

        if($level&&$level['id']!=$user_info['level_id']){//升级了就改变等级
            $user_model->fieldUpdate("level_id",$level['id'],$user_info['id']);
        }
    }
}
/**
 * 格式化参数格式化成url参数
 */
function ToUrlParams($values)
{
    $buff = "";
    foreach ($values as $k => $v)
    {
        if($k != "sign" && $v != "" && !is_array($v)){
            $buff .= $k . "=" . $v . "&";
        }
    }

    $buff = trim($buff, "&");
    return $buff;
}
/**
 * 生成签名 - 重写该方法
 * @param WxPayConfigInterface $config  配置对象
 * @param bool $needSignType  是否需要补signtype
 * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
 */
//A
function MakeSign($values)
{
    $config=[
        'key'=>"hyhy1213hyhy1213hyhy1213hyhy1213"
    ];
    //签名步骤一：按字典序排序参数
    ksort($values);
    $string = ToUrlParams($values);
    //签名步骤二：在string后加入KEY
    $string = $string . "&key=".$config['key'];
    //签名步骤三：MD5加密或者HMAC-SHA256
    if(strlen($values['sign']) <= 32){
        //如果签名小于等于32个,则使用md5验证
        $string = md5($string);
    } else {
        //是用sha256校验
        $string = hash_hmac("sha256",$string ,$config['key']);
    }
    //签名步骤四：所有字符转为大写
    $result = strtoupper($string);
    return $result;
}
//检查是否有已分配待支付的订单
function check_data($data){
    $buy_list =[];
    $ocean_list = [];
    foreach ($data as $key=>$value){
        if($value['status']>2||$value['is_overdue'] == 3){//订单状态大于 说明已经到了国际到货的阶段 或者订单已经发布到商城了就不能分配了

            return false;
        }
        if($value['status']==2&&$value['pay_status']==2){ //已分配已支付的订单 不能重新分配

        }
        else if($value['status'] == 2&&$value['pay_status']==1){

            array_push($ocean_list,$value['id']);
            if($value['order_type']==2){//一键代买的话直接把消息状态改为 未分配的状态 remark赋值为空
                array_push($buy_list,$value['message_id']);
            }
            if($value['order_type']==1){//拼单海淘的话 如果只分配了一件 就给该件赋值为未分配的状态并且赋值为空
                $count = (new \app\admin\model\OceanOrder())->where('relation_id','eq',$value['relation_id'])->count();
                if($count<=1){
                    array_push($buy_list,$value['message_id']);
                }
            }
        }
    }
    if(count($ocean_list)>0){
        $res= (new \app\admin\model\OceanOrder())->where('id','in',$ocean_list)->update(['relation_id'=>0,'status'=>1]);
        if(!$res){
            return false;
        }
    }

    if(count($buy_list)>0){
        $res= (new \app\admin\model\AlbumPhotoMessage())->where('id','in',$buy_list)->update(['remark'=>"",'apply_status'=>1]);
        if(!$res){
            return false;
        }
    }
    return true;
}
//修改购物车
function change_cart($cartId,$user_id) {

    $cart_model = new \app\index\model\SubstituteCart();
    $where_cart = [
        ['user_id','eq',$user_id],
        ['id','in',$cartId]
    ];
    $res =$cart_model->where($where_cart)->setField("delete_time",time());
    if(!$res){
        return false;
    }
    return true;
}
// 修改订单
function change_order($order_id){
    $model = new \app\index\model\SubstituteOrderDetails();

    $ocean_order_model = new \app\index\model\OceanOrder();
    $list = $model->selectList([['order_id','eq',$order_id]],"id,user_id,product_id");
    if(count($list)>0){
    }else{
        return false;
    }
    $product_id= [];
    //先修改购物车 在修改商品状态
    foreach ($list as $value){
        array_push($product_id,$value['product_id']);
    }

    //删除完购物车 给商品修改状态
    $res = $ocean_order_model->where("id","in",$product_id)->setField("is_buy",2);
    if(!$res){
        return false;
    }
    return true;
}
// 二次支付时候检查订单里面的商品是否已经支付过了
function check_order($order_id){
    $model = new \app\index\model\SubstituteOrderDetails();
    $list = $model->selectListWith("ocean",[['order_id','eq',$order_id]]);
    foreach ($list as $value){
        if($value['is_buy']==2){//有商品已被购买重新下单
            return false;
        }
    }
    return true;
}
// 首次支付的时候检查购物车里面的商品是否支付过了
function check_cart_list($cartId){
    $model = new \app\index\model\SubstituteCart();
    $list = $model->selectListWith("ocean",[['id','in',$cartId]]);
    foreach ($list as $value){
        if($value['is_buy']==2){//有商品已被购买重新下单
            return false;
        }
    }
    return true;
}
/**
 * @param $code
 * @param $errorCode
 * @param $data
 * @param $msg
 * @return \think\response\Json
 */
function getRandNumber($length){
    $str = null;
    $strPol = "0123456789";
    $max = strlen($strPol)-1;

    for ($i=0;$i<$length/2;$i++){
        $str .= $strPol[rand(0,$max)];
    }
    $unixTime = (String)strtotime('now');
    $unixTimeMax = strlen($unixTime) -1;
    for ($i=0;$i<$length/2;$i++){
        $str .= $unixTime[rand(0,$unixTimeMax)];
    }
    return $str;
}
function writeJson($code, $data=[], $msg = 'ok', $errorCode = 0)
{
    $data = [
        'error_code' => $errorCode,
        'result' => $data,
        'msg' => $msg
    ];
    return json($data, $code);
}
//通过关联id  将两个数组 变成从属关系的 二维数组
function arrayLevel($array1,$array2,$relation){
    foreach ($array1 as $key=>$value){
        $array1[$key]['itemList'] =[];
        foreach ($array2 as $ke=>$val){
            if($value[$relation]==$val[$relation]){
                array_push($array1[$key]['itemList'],$val);
            }
        }
        if(count($array1[$key]['itemList'])==0){
            unset($array1[$key]);
        }
    }
    return $array1;
}
/**
 *warehouse_id 仓库id  change_type 变动类型  1是加2是减，detail 是需要变动的数组
 */
function warehouseChangeStock($warehouse_id,$change_type,$detail){
    $product_id_list = array_column($detail,"product_id");//产品id
    $product_id_list = array_unique($product_id_list);//去重product_id
    $product_list = (new \app\admin\model\WarehouseGeneral())->selectList([['product_id','in',$product_id_list],['warehouse_id','eq',$warehouse_id]]);//已存在的仓库商品

    $newList = [];
    foreach ($product_list as $value){ $newList[$value['product_id']] = $value; }
    $where_sku = [
       ['product_id','in',$product_id_list],
       ['warehouse_id','eq',$warehouse_id]//属于该仓库的id
    ];

    $product_detail = (new \app\admin\model\WarehouseGeneralSku())->selectList($where_sku,"id,product_id,list_detail_id,stock");
    $addProduct = [];//添加的产品
    $editProduct = [];//修改的产品
    $addDetail = [];//添加的产品下的sku 的详情
    $editDetail = [];//修改产品下的sku 详情
    foreach ($detail as $key=>$value){
        $add = 0;
        foreach ($product_detail as $ke=>$val){
            if($value['id']==$val['list_detail_id'] && $value['product_id']==$val['product_id']){//匹配到了说明数据库里有该数据
                $add++;
                if($change_type==1){
                    $val['stock']+=$value['actual_stock'];
                }else{
                    $val['stock']-=$value['actual_stock'];
                }
                if($val['stock']<0){
                    return ['code'=>0,'msg'=>$value['sku'].'库存不足'];
                }
                $editDetail[] = [
                    'id' =>$val['id'],
                    'warn_time'=>isset($value['warning_time'])?$value['warning_time']:time(),
                    'warn_stock'=>isset($value['warning_stock'])?$value['warning_stock']:0,
                    'product_time'=>isset($value['product_time'])?$value['product_time']:time(),
                    'update_time'=>time(),
                    'stock' =>$val['stock']
                ];
            }
        }
        if($add==0){ //不存在做新增
            if($change_type==1){
                $addDetail[] = [
                    'product_id'=>$value['product_id'],
                    'sku' =>$value['sku'],
                    'stock'=>$value['actual_stock'],
                    'warehouse_id'=>$warehouse_id,
                    'warn_time'=>isset($value['warning_time'])?$value['warning_time']:time(),
                    'warn_stock'=>isset($value['warning_stock'])?$value['warning_stock']:0,
                    'product_time'=>isset($value['product_time'])?$value['warning_time']:time(),
                    'create_time' =>time(),
                    'update_time'=>time(),
                    'list_detail_id'=>$value["id"],
                    'uid'=>$value["uid"],
                ];
            }else{
                return ['code'=>0,'msg'=>$value['sku'].'库存不足'];
            }
        }
        //判断商品是否存在
        if(isset($newList[$value['product_id']])){
            if(isset($editProduct[$value['product_id']])){
                if($change_type==1){
                    $editProduct[$value['product_id']]['stock']+=$value['actual_stock'];
                }else{
                    $editProduct[$value['product_id']]['stock']-=$value['actual_stock'];
                }

            }else{
                if($change_type==1){
                    $stock = $newList[$value['product_id']]['stock']+$value['actual_stock'];
                }else{
                    $stock = $newList[$value['product_id']]['stock']-$value['actual_stock'];
                }
                $editProduct[$value['product_id']] = [
                    'id' =>$newList[$value['product_id']]['id'],
                    'stock'=>$stock,
                    'warehouse_batches'=>$newList[$value['product_id']]['warehouse_batches']+1,
                    'update_time'=>time()
                ];
            }
            if($editProduct[$value['product_id']]['stock']<0){
                return ['code'=>0,'msg'=>'商品库存不足'];
            }
        }else{
            if(isset($addProduct[$value['product_id']])){
                if($change_type==1){
                    $addProduct[$value['product_id']]['stock']+=$value['actual_stock'];
                }else{
                    $addProduct[$value['product_id']]['stock']-=$value['actual_stock'];
                }
            }else{
                if($change_type==2){
                    return ['code'=>0,'msg'=>'商品库存不足'];
                }
                $addProduct[$value['product_id']] = [
                    'uid'        =>(new \app\admin\model\Product())->findOne([['id','eq',$value['product_id']]],"uid"),
                    'product_id' =>$value['product_id'],
                    'stock'=>$value['actual_stock'],
                    'warehouse_batches'=>1,
                    'warehouse_id' =>$warehouse_id,
                    'create_time' =>time(),
                    'update_time'=>time()
                ];
            }
            if($addProduct[$value['product_id']]['stock']<0){
                return ['code'=>0,'msg'=>'商品库存不足'];
            }
        }
    }
    //添加商品
    if(count($addProduct)>0){
        $res = (new \app\admin\model\WarehouseGeneral())->saveAll($addProduct);
        if(!$res){
            return ['code'=>-1,'msg'=>'仓库添加新商品失败'];
        }
    }
    //修改商品
    if(count($editProduct)>0){
        $res = (new \app\admin\model\WarehouseGeneral())->saveAll($editProduct);
        if(!$res){
            return ['code'=>-1,'msg'=>'仓库修改商品库存失败'];
        }
    }
    //添加商品sku
    if(count($addDetail)>0){
        $res = (new \app\admin\model\WarehouseGeneralSku())->saveAll($addDetail);
        if(!$res){
            return ['code'=>-1,'msg'=>'仓库商品sku新增失败'];
        }
    }
    //修改商品sku
    if(count($editDetail)>0){
        $res = (new \app\admin\model\WarehouseGeneralSku())->saveAll($editDetail);
        if(!$res){
            return ['code'=>-1,'msg'=>'仓库商品sku修改失败'];
        }
    }
    return ['code'=>'1','msg'=>'添加成功'];
}

//商品去库存
function orderChangeStock($product_id,$number,$warehouse_id){
    //查看预警日期最近的仓库
    $where["product_id"] = $product_id;
    $newGeneralSkuList = []; //批次待处理
    $newGeneralList = [];    //总库存待处理
    $warehouseGeneralSkuService = (new \app\admin\model\WarehouseGeneralSku());
    $warehouseGeneralService = (new \app\admin\model\WarehouseGeneral());

    //获取当前商品所有库存非0批次
    $where = [];
    $where[] = ["stock","gt",0];
    $where[] = ["product_id","eq",$product_id];
    $where[] = ["warehouse_id","eq",$warehouse_id];

    $nowList = $warehouseGeneralSkuService
        ->field("id,product_id,sku,stock,warehouse_id,warn_stock,warn_time,product_time,list_detail_id")
        ->where($where)->order("warn_time asc")->select()->toArray();

    //当前总共退货数量
    $number1 = $number;
    //计算批次库存更改
    foreach ($nowList as $k1=>$v1){
        if(($number1 - $v1["stock"]) > 0){
            $number1 = $number1 - $v1["stock"];
            $v1["stock"] = 0;
            $v1["update_time"] = time();
        }else{
            $v1["stock"] = $v1["stock"] - $number1;
            $v1["update_time"] = time();
            $number1 = 0;
        }
        array_push($newGeneralSkuList,$v1);
        if($number1 == 0){
            break;
        }
    }
    if($number1 > 0){
        Db::rollback();
        return ['code'=>-1,'msg'=>'操作失败,当前各批次库存不足'];
    }

    //计算总库存更改
    $number2 = $number;
    $generalWhere = [];
    $generalWhere[] = ["product_id","eq",$product_id];
    $generalWhere[] = ["warehouse_id","eq",$warehouse_id];
    $nowGeneral = $warehouseGeneralService
        ->field("id,uid,product_id,stock,warehouse_batches,status,admin_id,warehouse_id")
        ->where($generalWhere)->find()->toArray();
    $nowGeneral["stock"] = $nowGeneral["stock"] - $number2;
    if($nowGeneral["stock"] < 0){
        Db::rollback();
        return ['code'=>-1,'msg'=>'修改失败,总仓库库存不足'];
    }
    array_push($newGeneralList,$nowGeneral);

    //更新批次仓库
    $res = $warehouseGeneralSkuService->fieldUpdateAll($newGeneralSkuList);
    if(!$res){
        Db::rollback();
        return ['code'=>-1,'msg'=>'修改批次库存失败'];
    }
    //更新总仓库
    $res = $warehouseGeneralService->fieldUpdateAll($newGeneralList);
    if(!$res){
        Db::rollback();
        return ['code'=>-1,'msg'=>'修改总仓库库存失败'];
    }
    Db::commit();
    return ['code'=>1,'msg'=>'操作成功'];
}

function changeArrayKey($array,$keyName){
    $newData = [];
    foreach ($array as $key=>$value){
        $newData[$value[$keyName]] = $value;
    }
    return $newData;
}
function array_sort($arr,$keys,$type='asc'){
    $keysvalue = $new_array = array();
    foreach ($arr as $k=>$v){
        $keysvalue[$k] = $v[$keys];
    }
    if($type == 'asc'){
        asort($keysvalue);
    }else{
        arsort($keysvalue);
    }
    reset($keysvalue);
    foreach ($keysvalue as $k=>$v){
        $new_array[$k] = $arr[$k];
    }
    return $new_array;
}
function getWarehouseId($shop){
    if($shop['type']==1){
        $warehouse_id = 3;
    }elseif($shop['type']==3){
        $warehouse_id = 1;
    }else{
        $warehouse_id = (new \app\admin\model\Warehouse())->where([['uid','eq',$shop['id']]])->value('id');
    }
    return $warehouse_id;
}
//微信退款
function wxreFund($data,$source){
    if($source==1){
        $wxConfig = require_once PAY_PATH . '/wxconfig.php';

    }else{
        $wxConfig = require_once PAY_PATH . '/wxappconfig.php';
    }
    try {
        $ret = \Payment\Client\Refund::run("wx_refund", $wxConfig, $data);
        return $ret ;
    } catch (\Payment\Common\PayException $e) {
        echo $e->errorMessage();
        exit;
    }
}
//支付宝退款
function alireFund($data,$source){
    if($source==1){
        $aliConfig = require_once ALI_PATH . '/webaliconfig.php';

    }else{
        $aliConfig = require_once ALI_PATH . '/aliconfig.php';
    }
    try {
        $ret = \Payment\Client\Refund::run("ali_refund", $aliConfig, $data);
        return $ret ;
    } catch (\Payment\Common\PayException $e) {
        //总订单支付
        SystemLog::record("[退款异常]当前订单".$data["out_trade_no"]."产生异常：" . $e->errorMessage(), 'alert');
        echo $e->errorMessage();
        exit;
    }
}
function getAdminAuth($level,$account_type){
    $auth = [];
    $where_auth = [
        ['type','elt',$level],
        ['account_type','eq',$account_type]
    ];
    $list = (new \app\admin\model\AuthRule())->selectList($where_auth,"id,pid,title,rule_val,rule_url,account_type,type","sort desc");
    $list = $list->toArray();
    foreach ($list as $value){
        if($value['type']==1){
            if($level>=2){
                $value['itemList'] = [];
            }
            $auth[$value['id']] = $value;
        }
    }
    if($level>=2){
        foreach ($list as $value){
            if($value['type']==2){
                if($level>=3){
                    $value['itemList'] = [];
                }
                $auth[$value['pid']]['itemList'][$value['id']] = $value;
            }
        }
    }
    if($level>=3){
        foreach ($list as $value){
            if($value['type']==3){
                foreach ($auth as &$val){
                    if(isset($val['itemList'][$value['pid']])){
                        $val['itemList'][$value['pid']]['itemList'][] = $value;
                    }
                }
            }
        }
    }
    foreach ($auth as &$value){
        if(isset($value['itemList'])){
            $value['itemList']=array_values($value['itemList']);
        }
    }
    $auth = array_values($auth);
    return $auth;
}
